package com.yaosheng.thread.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * Created by yaosheng on 2021/7/1.
 */
public class Test04 {

    volatile List lists = new ArrayList ();

    public void add(Object o){
        lists.add (o);
    }

    public int size(){
        return lists.size ();
    }

    public static void main(String[] args) {

        Test04 test04 = new Test04 ();

        Thread t2 = new Thread ( () -> {

            System.out.println ("t2启动");
            if(test04.size () != 5){
                LockSupport.park ();
            }
            System.out.println ("t2结束");

        },"t2");
        t2.start ();

        try{
            TimeUnit.SECONDS.sleep (1);
        }catch (InterruptedException e){
            e.printStackTrace ();
        }

        new Thread ( () -> {

            System.out.println ("t1启动");
            for(int i = 0;i < 10;i ++){
                test04.add (new Object ());
                System.out.println ("add" + i);
                if(test04.size () == 5){
                    LockSupport.unpark (t2);
                }
                try{
                    TimeUnit.SECONDS.sleep (1);
                }catch (InterruptedException e){
                    e.printStackTrace ();
                }
            }
        },"t1").start ();
    }
}
